package com.hongkuncheng.cms.controller.admin;

import java.io.File;
import java.util.List;

import org.hibernate.LockMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.FileHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.Homepage;
import com.hongkuncheng.cms.model.Datamodel;
import com.hongkuncheng.cms.model.Webinfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 主页频道管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/homepage")
public class AhomepageController extends BaseController {

    // 主页频道编辑
    @RequestMapping
    public String index() {
        int homepageId = request.getParameter("homepageid") == null ? 1 :
                Integer.parseInt(request.getParameter("homepageid"));
        List<Datamodel> datamodels = factorySession.createCriteria(Datamodel.class)
                .add(Restrictions.eq("datamodelType.id", 1))
                .list();
        if (datamodels.size() == 0) {
            PageHelper.alertAndGoBack("未找到可用的其它类数据模型");
            return null;
        }
        Homepage homepage = factorySession.get(Homepage.class, homepageId);
        request.setAttribute("homepage", homepage);
        request.setAttribute("datamodels", datamodels);
        webinfo = factorySession.get(Webinfo.class, 1);
        List<File> templatefiles = FileHelper.getFiles(applicationDirectory + "/template/" + webinfo.getTemplate() + "/");
        request.setAttribute("templatefiles", templatefiles);
        return view();
    }

    // 主页频道编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("yunwei_webmaintain_homepage");
        int homepageId = Integer.parseInt(request.getParameter("homepageid"));
        int datamodelid = Integer.parseInt(request.getParameter("datamodelid"));
        String template = request.getParameter("template");
        Homepage homepage = factorySession.load(Homepage.class, homepageId, LockMode.PESSIMISTIC_WRITE);
        homepage.setDatamodel(factorySession.load(Datamodel.class, datamodelid));
        homepage.setTemplate(template);
        recordLog("更新" + homepage.getName() + "频道《" + homepage.getName().trim() + "》");
        PageHelper.confirmAndRedirect("保存成功，是否生成相关静态页面？",
                "../createpage/zhuantifilepaths?zhuantiids=" + homepageId + "&temp=1",
                "../homepage/?homepageid=" + homepageId);
    }

}
